﻿(function ($) {

    $(function () {
        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", Getlatestcomment('#latestcomment .list-group'));
        });
    });

    /*javascript for latestcomment*/
    this.Getlatestcomment = function (idcontent) {
        $('#latestcommentloading').show();
        var itemrowlimit = 5;
        var clientContext = new SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var oList = web.get_lists().getByTitle('Comments');
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><Query><Where><IsNotNull><FieldRef Name=\'ID\' /></IsNotNull></Where><OrderBy><FieldRef Name=\'Modified\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>' + itemrowlimit + '</RowLimit></View>');
        var items = oList.getItems(camlQuery);
        clientContext.load(web);
        clientContext.load(items, "Include(Title,PostTitle, Author)");
        clientContext.executeQueryAsync(
            function () {
                $(idcontent).html('');
                $('#latestcommentloading').hide();
                var listEnumerator = items.getEnumerator();
                while (listEnumerator.moveNext()) {
                    var item = listEnumerator.get_current();
                    var postlink = web.get_url() + '/Lists/Posts/Post.aspx?ID=' + item.get_item('PostTitle').get_lookupId();
                    var userlink = web.get_url() + '/_layouts/15/userdisp.aspx?ID=' + item.get_item('Author').get_lookupId();
                    var comment = buildlatestcomment(userlink, item.get_item('Author').get_lookupValue(), item.get_item('Title'), postlink, item.get_item('PostTitle').get_lookupValue());
                    $(idcontent).append(comment);
                }
                if ($(idcontent).html() == "")
                { $(idcontent).html('There are no comments for this category.'); }
            }, function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };

    this.buildlatestcomment = function (userlink, usercomment, commenttitle, postlink, posttitle) {

        var commentitem = '';
        commentitem += ' <li class="list-group-item">';
        commentitem += '<span class="greenArrow"></span><a href="' + userlink + '">' + replaceUserNameNguyenThiThanhHien(usercomment) + '</a> ';
        commentitem += '<span> ' + commenttitle + '</span> ';
        if (posttitle != null && posttitle != "") {
            commentitem += '<span> in <a href="' + postlink + '">' + posttitle + '</a></span>';
        }
        commentitem += ' </li>';
        return commentitem;
    };

}).call(this, jQuery);